package org.proddevplm.business.openRoom;

import java.util.List;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;

import java.util.Map;

import org.proddevplm.business.api.AController;
import org.proddevplm.business.openRoom.constants.OpenRoomConstants;
import org.proddevplm.constants.ControllerConstants;
import org.proddevplm.constants.UserConstants;
import org.proddevplm.dao.data.Project;
import org.proddevplm.dao.data.User;
import org.proddevplm.dao.data.openRoom.ChatMessage;

public class OpenRoomController extends AController {

	@Override
	public Object execute(int command, Object data) {
		Object returnObject = null;
		Map<String, Object> openRoomMap = (Map<String, Object>) data;
		User userAux = (User) getSession().getAttribute(UserConstants.USER);
		int projectId = (Integer) getSession().getAttribute("projectId");
		Project project = getDaoManager().getProjectManager()
				.getProjectByProjectId(projectId);
		User user = getDaoManager().getUserManager().getUser(userAux.getId());
		String roomName = (String) openRoomMap.get("roomName"); 
		
		
		switch (command) {

		case OpenRoomConstants.CHAT:
			try {
				ChatMessage chatMessage = new ChatMessage();
				chatMessage.setProject(project);
				chatMessage.setUser(user);
				chatMessage.setMessage(openRoomMap.get("userMessage")
						.toString());
				chatMessage.setRoomName(roomName);
				System.out.println("Trying to persist: "
						+ chatMessage.getMessage());
				getDaoManager().getOpenRoomManager().addChatMsg(chatMessage);

			} catch (Exception e) {
				e.printStackTrace();
			}

			break;
		case OpenRoomConstants.GET_ALL_MESSAGES:
			try {
				String getFromString = openRoomMap.get("getFrom").toString();
				String stringResult;
				int index = 0;

				if (getFromString != null) {
					try {
						index = Integer.valueOf(getFromString);
					} catch (NumberFormatException e) {

					}
				}

				List<ChatMessage> result = getDaoManager().getOpenRoomManager()
						.getMessages(index, projectId, roomName);

				if (result.size() > 0) {
					int lastIndex = result.get(result.size() - 1).getId();
					/*
					 * { 'lastindex': 4, 'messages': [ {'value': "message1"},
					 * {'value': "message2"}, {'value': "message3"} ] }
					 */
					stringResult = "{ \"lastindex\": " + lastIndex
							+ ",\"messages\":[";
					int i = 0;
					for (ChatMessage chatMessage : result) {
						if (i++ < result.size() - 1) {
							stringResult += "{\"value\": \""
									+ chatMessage.getMessage().replaceAll("\"",
											"'") + "\", \"userId\":"
									+ user.getId() + "},";
						} else {
							stringResult += "{\"value\": \""
									+ chatMessage.getMessage().replaceAll("\"",
											"'") + "\", \"userId\":"
									+ user.getId() + "}";
						}
					}
					stringResult += "]}";
					returnObject = stringResult;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
			
		case OpenRoomConstants.GET_ROOM_NAMES:
			
			List<String> cm = getDaoManager().getOpenRoomManager().getRoomNamesByProjectId(projectId);
			String roomNames = "";
			try {
			for(String c:cm){
				if (!"default".equals(c))
					roomNames+=c+"~";
			}
			roomNames = roomNames.substring(0, roomNames.length()-1);
			
			putOnState(ControllerConstants.NEXT_PAGE,"content/project/projectPage.jsp");
			putOnSession("currentTab", "tab8");
			} catch (Throwable e)
			{
				e.printStackTrace();
			}
			return roomNames;
			
		}

		putOnState(ControllerConstants.NEXT_PAGE,
				"content/project/projectPage.jsp");
		putOnSession("currentTab", "tab8");

		return returnObject;
	}

}
